package com.sam.im.heiqun.service;

import android.app.Activity;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;

import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.ToolsUtils;

/**
 * Created by Joe on 2017/2/27.
 * 心跳
 */

public class IMIntentService extends IntentService {

    private UserEntivity userEntivity;
    private Activity activity;
    static PowerManager.WakeLock mWakeLock;

    //申请设备电源锁
    public static void acquireWakeLock(Context context) {
        if (null == mWakeLock) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "WakeLock");
            if (null != mWakeLock) {
                mWakeLock.acquire();
            }
        }
    }
    //释放设备电源锁
    public static void releaseWakeLock() {
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     */
    public IMIntentService() {
        super("IMIntentService");

    }

    @Override
    public void onCreate() {
        super.onCreate();
        acquireWakeLock(this);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //这里执行耗时操作
        ImMessage imMessage = new ImMessage();
        imMessage.setDevType(1);
        imMessage.setMessageType(31);
        userEntivity = ToolsUtils.getUser();
        if (userEntivity != null) {
            imMessage.setFromid(userEntivity.getId());//推出登陆后数据删除  这里判断是否为空
        }
        while (!App.isManualLogout) {
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (App.socket != null && App.socket.connected()) {
                App.socket.emit("heart", IMMessageToJson.changeJSONObject(imMessage));
            } else {
                if (App.socket != null) {
                    App.socket.close();
                }
                App.socket = null;
                if (!App.isManualLogout) {
                    Log.i("info","心跳链接");
                    App.initSocket(App.imIpAfterReady, App.tokenAfterReady);
                }
            }
        }
    }
    @Override
    public void onDestroy() {//被销毁的时候关闭当前这个应用
        super.onDestroy();
        Log.i("fanhui","adasdds");
        releaseWakeLock();
        if (!App.isManualLogout) {
            //退出app
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}
